package com.cctv.custom.hibernate.integrated.wrapper;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class BookServiceImpl implements BookService {

	@Resource
	private CommonDao dao;

	@Override
	public void saveOrUpdate(Book book) {
		dao.saveOrUpdate(book);
	}

	@Override
	public List<Book> list() {
		List<Criterion> criterions = new ArrayList<Criterion>();
		return dao.list(Book.class, criterions);
	}

	@Override
	public List<Book> listOrderByPriceDesc() {
		List<Criterion> criterions = new ArrayList<Criterion>();
		return dao.list(Book.class, criterions,
				new Order[] { Order.desc("price") });
	}

	@Override
	public List<Book> listOrderByPriceAsc() {
		List<Criterion> criterions = new ArrayList<Criterion>();
		return dao.list(Book.class, criterions,
				new Order[] { Order.asc("price") });
	}

	@Override
	public List<Book> list(String name, String author, Double price) {
		List<Criterion> criterions = new ArrayList<Criterion>();
		if (StringUtils.isNotBlank(name)) {
			criterions.add(Restrictions.eq("name", name));
		}
		if (StringUtils.isNotBlank(author)) {
			criterions.add(Restrictions.eq("author", author));
		}
		if (price != null) {
			criterions.add(Restrictions.eq("price", price));
		}
		return dao.list(Book.class, criterions);
	}

	@Override
	public List<Book> list(String author, int pageIndex, int pageSize) {
		List<Criterion> criterions = new ArrayList<Criterion>();
		if (StringUtils.isNotBlank(author)) {
			criterions.add(Restrictions.eq("author", author));
		}
		return dao.list(Book.class, criterions, pageIndex, pageSize,
				new Order[] { Order.desc("price") });
	}
}
